<template>
  <div class="login">
    <cube-form :model="model" :schema="schema" @submit="submitHandler"></cube-form>

  </div>
</template>

<script>
import { Toast } from 'cube-ui';


export default {
  data() {
    return {
      model: {
        username: "",
        password: ""
      },
      schema: {
        fields: [
          {
            type: 'input',
            modelKey: 'username',
            label: '用户名',
            props: {
              placeholder: '请输入用户名'
            },
            rules: {
              required: true
            },
            // validating when blur
            trigger: 'blur'
          },
          {
            type: 'input',
            modelKey: 'password',
            label: '密码',
            props: {
              placeholder: '请输入密码',
              type: "password",
              eye: {
                open: false
              }
            },
            rules: {
              required: true
            },
            // validating when blur
            trigger: 'blur'
          },
          {
            type: 'submit',
            label: '登录'
          }
        ]

      }
    }
  },
  methods: {
    async submitHandler(e) {
      e.preventDefault();
      //默认密码登录
      let param = this.model;
      param.type = 1;
      const result = this.$http.post("/wx/user/login", param)
        .then(response => {
          var data = response.data;
          //console.log(data);
          if (response.status != 200 || data.code != '200') {
            const toast = this.$createToast({
              time: 3000,
              txt: data.message,
              type: 'txt'
            })
            toast.show()
          }

          //登录成功
          if (data.code == '000000') {
            //console.log(data);
            const toast = this.$createToast({
              time: 1000,
              txt: '登录成功',
              type: 'txt'
            });

            //存储token至vuex
            var token  = data.result.token;
            this.$store.commit('setToken', token);
            window.localStorage.setItem("token", token);
            toast.show();

            //调整首页
            this.$router.push({
              path: '/index'
            });
          }
        })
        .catch(error => {
          console.error(error);
        });
    }
  }
}

</script>

<style lang="stylus">

</style>